/*
 * generator.c
 * Code generator for uPL0c.
 *
 * Copyright 2024 dh33ex <dh33ex@riseup.net>
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
 * MA 02110-1301, USA or visit <http://www.gnu.org/licenses/>.
 *
 *
 */

#include "generator.h"
#include "scaner.h"
#include "gios.c"

#include <stdio.h>

unsigned int RH = 1;        /* register pointer */
unsigned int SP = 14;       /* number of register that store a stack pointer */
unsigned int SB = 13;       /* number of register that store a static base */
unsigned int LNK = 15;      /* number of register that store a link */

unsigned int PC = 0;        /* variable that stores current position in memory */

/* value in words! */
unsigned int PROC = PROCEDURE_START_ADDR;  /* variable that stores next free position for procedures */

unsigned int code[MEMORY_SIZE];


void put_f0(unsigned int op, unsigned int reg1, unsigned int reg2, unsigned int reg3) {
    code[PC++] = ((reg1 * 0x10 + reg2) * 0x10 + op) * 0x10000 + reg3;

    if (PC >= MEMORY_SIZE) {
        print_error("memory exhausted");
        PC = 0; /* woraround to prevent "Segmentation failed" */
    }
}


void put_f1(unsigned int op, unsigned int reg1, unsigned int reg2, unsigned int im) {
    code[PC++] = ((((4 + (im < 0 ? 1 : 0)) * 0x10 + reg1) * 0x10 + reg2) * 0x10 + op) * 0x10000 + (im & 0xFFFF);

    if (PC >= MEMORY_SIZE) {
        print_error("memory exhausted");
        PC = 0; /* woraround to prevent "Segmentation failed" */
    }
}


void put_f2(unsigned int op, unsigned int reg1, unsigned int reg2, unsigned int off) {
    code[PC++] = (((8 + op) * 0x10 + reg1) * 0x10 + reg2) * 0x100000 + (off & 0xFFFFF);

    if (PC >= MEMORY_SIZE) {
        print_error("memory exhausted");
        PC = 0; /* woraround to prevent "Segmentation failed" */
    }
}


int put_f3(unsigned int op, unsigned int cond, unsigned int off_reg) {
    /*
     * op = uv
     * op = 0v; off_reg -> reg
     * op = 1v; off_reg -> off
     */

    code[PC] = ((0xC + op)*0x10 + cond) * 0x1000000 + (off_reg & 0xFFFFFF);

    if (PC+1 >= MEMORY_SIZE) {
        print_error("memory exhausted");
        PC = 0; /* woraround to prevent "Segmentation failed" */
    }

    return PC++;
}
